import type { SortOrder } from "mongoose";
export default defineEventHandler(async (event) => {
  const queryObj = getQuery(event);
  const { orderBy = "createdAt", order = "desc" } = queryObj;
  const customSort = {
    [orderBy as string]: order as SortOrder,
  };
  const currentPage = Number(queryObj.currentPage) || 1;
  const pageSize = Number(queryObj.pageSize) || 10;
  const skip = (currentPage - 1) * pageSize;
  const findCondition: {
    [key: string]: any;
  } = {};
  if (queryObj.name) {
    findCondition.name = {
      // 模糊匹配
      $regex: queryObj.name,
    };
  }
  if (queryObj.code) {
    findCondition.code = {
      // 模糊匹配
      $regex: queryObj.code,
    };
  }
  const res_list = await DicSchema.find(findCondition)
    .select(["name", "code", "list", "createdAt"])
    .skip(skip)
    .limit(pageSize)
    .sort(customSort)
    .lean();
  const total = await DicSchema.find(findCondition).countDocuments();
  return {
    data: res_list,
    total,
    pageSize,
    currentPage,
  };
});
